package com.kefu.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kefu.entity.Message;
import com.kefu.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatHandler extends TextWebSocketHandler {

    // 存储所有连接 (key: role_userId, value: session)
    public static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();

    @Autowired
    private ChatService chatService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        // 分别获取用户ID和客服ID（根据角色二选一）
        String userId = (String) session.getAttributes().get("userId");
        String adminId = (String) session.getAttributes().get("adminId");
        String role = (String) session.getAttributes().get("role");

        // 基础角色校验
        if (role == null) {
            closeSession(session, "缺少角色参数（role）");
            return;
        }

        // 按角色处理ID参数
        String identityId; // 统一标识ID（用户用userId，客服用adminId）
        if ("user".equals(role)) {
            // 用户角色必须有userId
            if (userId == null || userId.isEmpty()) {
                closeSession(session, "用户连接缺少userId参数");
                return;
            }
            identityId = userId;
            System.out.printf("用户[%s]WebSocket连接建立%n", identityId);
        } else if ("admin".equals(role)) {
            // 客服角色必须有adminId，忽略userId（允许为null）
            if (adminId == null || adminId.isEmpty()) {
                closeSession(session, "客服连接缺少adminId参数");
                return;
            }
            identityId = adminId;
            // 客服上线时更新状态
            chatService.updateAdminStatus(identityId, 1); // 1-在线
            System.out.printf("客服[%s]WebSocket连接建立%n", identityId);
        } else {
            closeSession(session, "无效角色（仅支持user/admin）");
            return;
        }

        // 存储会话（key格式：role_identityId）
        SESSIONS.put(role + "_" + identityId, session);
    }

    // 封装关闭会话的工具方法
    private void closeSession(WebSocketSession session, String reason) {
        System.out.println("WebSocket连接关闭：" + reason);
        try {
            session.close(CloseStatus.POLICY_VIOLATION.withReason(reason));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        try {
            TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
            Map<String, Object> msgData = objectMapper.readValue(message.getPayload(), typeRef);
            Map<String, Object> messageData = (Map)msgData.get("data");
            Message msg = new Message();
            msg.setSessionId((String) messageData.get("sessionId"));
            msg.setSenderId((String) messageData.get("senderId"));
            msg.setContent((String) messageData.get("content"));
            msg.setMessageType((Integer) messageData.get("messageType"));
            msg.setSenderType((Integer) messageData.get("senderType"));
            //msg.setSenderType("user".equals(MessageData.get("role")) ? 1 : 2);

            // 保存消息并转发
            chatService.saveAndForwardMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String userId = (String) session.getAttributes().get("userId");
        String role = (String) session.getAttributes().get("role");

        if (userId != null && role != null) {
            SESSIONS.remove(role + "_" + userId);
            if ("admin".equals(role)) {
                chatService.updateAdminStatus(userId, 0); // 离线
            }
        }
    }

    // 发送消息给指定用户
    public void sendMessage(String userId, String role, String message) throws IOException {
        WebSocketSession session = SESSIONS.get(role + "_" + userId);
        if (session != null && session.isOpen()) {
            session.sendMessage(new TextMessage(message));
        }
    }
}
